package leetcode.editor.cn.q1_300.q;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author qidi
 * @date 2021-11-18 16:16:03
 */
class Q0039_CombinationSum {

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> res = new ArrayList<>();
            Arrays.sort(candidates);
            if (candidates[0] > target) return res;
            process(candidates, target, res, 0, new ArrayList<Integer>(), 0);
            return res;
        }

        private void process(int[] candidates, int target, List<List<Integer>> res, int i, List<Integer> cur, int sum) {
            if (i == candidates.length) return;

            int newSum = sum + candidates[i];
            if (newSum == target) {
                cur.add(candidates[i]);
                res.add(cur);
            } else if (newSum > target) {
                return;
            } else {
                List<Integer> l1 = new ArrayList<>(cur);
                l1.add(candidates[i]);
                process(candidates, target, res, i, l1, newSum);

                List<Integer> l2 = new ArrayList<>(cur);
                process(candidates, target, res, i + 1, l2, sum);
            }
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new Q0039_CombinationSum().new Solution();
//        System.out.println(solution.combinationSum(new int[]{2, 3, 6, 7}, 7));
//        System.out.println(solution.combinationSum(new int[]{2, 3, 4, 5, 9}, 8));
//        System.out.println(solution.combinationSum(new int[]{2}, 3));
        System.out.println(solution.combinationSum(new int[]{2, 7, 6, 3, 5, 1}, 9));
    }
}